﻿using System;
using Loong.Domain.Entities;
using Loong.Domain.Entities.Auditing;
using Loong.Domain.Uow;
using Loong.Extensions;
using Loong.Runtime.Session;

namespace Loong.Dapper.Filters.Action
{
    public class CreationAuditDapperActionFilter : DapperActionFilterBase, IDapperActionFilter
    {
        public CreationAuditDapperActionFilter(
            ILoongSession loongSession,
            IGuidGenerator guidGenerator,
            ICurrentUnitOfWorkProvider currentUnitOfWorkProvider)
            : base(loongSession, guidGenerator, currentUnitOfWorkProvider)
        {
        }

        public void ExecuteFilter<TEntity, TPrimaryKey>(TEntity entity) where TEntity : class, IEntity<TPrimaryKey>
        {
            long? userId = GetAuditUserId();

            CheckAndSetId(entity);

            var entityWithCreationTime = entity as IHasCreationTime;
            if (entityWithCreationTime != null)
            {
                if (entityWithCreationTime.CreationTime == default(DateTime))
                {
                    entityWithCreationTime.CreationTime = DateTime.Now;
                }
            }

            if (userId.HasValue && entity is ICreationAudited)
            {
                var record = entity as ICreationAudited;
                if (record.CreatorUserId == null)
                {
                    record.CreatorUserId = userId;
                }
            }

            if (entity is IHasModificationTime)
            {
                entity.As<IHasModificationTime>().LastModificationTime = null;
            }

            if (entity is IModificationAudited)
            {
                var record = entity.As<IModificationAudited>();
                record.LastModifierUserId = null;
            }
        }
    }
}
